package com.cloneoner.test.slider.view 
{
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.ColorTransform;

	/**
	 * @author sdnvd
	 */
	public class Throbber extends Sprite {
		
		private var _wheel : Sprite;
		private var _teeth : int = 12;
		private var _angle : Number;
		private var _colour : int;
		private var _colTrans : ColorTransform;
		
		
		public function Throbber( c : int = 0x000000 )
		{
			_colour = c;

			_angle = 360 / _teeth;

			_init();
		}

		private function _init():void
		{
			_colTrans = new ColorTransform();
			_colTrans.color = _colour;

			_draw();

			addEventListener( Event.ADDED_TO_STAGE, _startRotation );
		}

		private function _draw():void
		{
			_wheel = new Sprite();

			for ( var i : int = 0; i < _teeth; i++ )
			{
				_wheel.addChild( _addTooth( i ) );
			}

			_wheel.transform.colorTransform = _colTrans;

			addChild( _wheel );
		}

		private function _addTooth( i : int ):Shape
		{
			var opacite : Number = ( 360 - ( ( i + 2 ) * ( _angle - 5 ) ) ) / 360;

			var tooth : Shape = new Shape();
			tooth.graphics.beginFill( 0x000000, opacite );
			tooth.graphics.drawRect( 5, -.5, 5, 1 );
			tooth.graphics.endFill();

			tooth.rotation = - ( i * _angle );

			return tooth;
		}

		// - - -
		private function _startRotation( e : Event ):void
		{
			removeEventListener( Event.ADDED_TO_STAGE, _startRotation );
			addEventListener( Event.REMOVED_FROM_STAGE, _stopRotation );

			addEventListener( Event.ENTER_FRAME, _doRotate );
		}

		private function _stopRotation( e : Event ):void
		{
			removeEventListener( Event.ENTER_FRAME, _doRotate );
			removeEventListener( Event.REMOVED_FROM_STAGE, _stopRotation );

			while ( _wheel.numChildren > 0 )
			{
				_wheel.removeChildAt( 0 );
			}

			removeChild( _wheel );
		}

		// - - -
		private function _doRotate( e : Event ):void
		{
			_wheel.rotation += 22;
		}
	}
}
